﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using Quartz;
using Quartz.Impl;
using System.Configuration;
using PayRoller.Code;
using HySoft.Cash;

namespace PayRoller
{
    public class Global : System.Web.HttpApplication
    {
        IScheduler scheduler;

        protected void Application_Start(object sender, EventArgs e)
        {
            /*
             * 本来账单的生产时通过配置好时间的任务，自动执行的。
             * 但是由于托管方空间有问题（App会经常推出）任务得不到执行，
             * 因此这个地方在每次应用启动的时候，都生成一次昨天的Invoice。
             */
            
            DataBaseLoger.SaveExcuteInfo("Other","App start");
            //1.使用任务执行Invoice任务
            StartInvoiceJob();
            //2.每次app启动，都执行Invoice任务
            SystemJob.ExecuteTask();
        }

        private void StartTimerJob()
        {
            TimerJob.Instance.Start();
        }

        private void StartInvoiceJob()
        {
            ISchedulerFactory factory = new StdSchedulerFactory();
            scheduler = factory.GetScheduler();
            JobDetail jobDetail = new JobDetail("InvoiceJob", null, typeof(SystemJob));
            int hourGetted = Convert.ToInt32(ConfigurationManager.AppSettings["InvoiceTaskExcuteHour"]);
            int minuteGetted = Convert.ToInt32(ConfigurationManager.AppSettings["InvoiceTaskExcuteMinute"]);
            Trigger triger = TriggerUtils.MakeDailyTrigger(hourGetted, minuteGetted);
            triger.Name = "InvoiceTriger";
            scheduler.ScheduleJob(jobDetail, triger);
            scheduler.Start();
        }

        private void StartSimpleJob()
        {
            ISchedulerFactory factory = new StdSchedulerFactory();
            scheduler = factory.GetScheduler();
            JobDetail jobDetail = new JobDetail("SimpleJob", null, typeof(SimpleJob));
            Trigger triger = TriggerUtils.MakeMinutelyTrigger();
            triger.Name = "SimpleTriger";
            scheduler.ScheduleJob(jobDetail, triger);
            scheduler.Start();
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {
            DataBaseLoger.SaveExcuteInfo("Other", "App quit");
            if (scheduler != null)
            {
                scheduler.Shutdown();
            }
        }
    }
}